home *** CD-ROM | disk | FTP | other *** search
/ Aminet 34 / Aminet 34 (2000)(Schatztruhe)[!][Dec 1999].iso / Aminet / util / gnu / unixcmds.lha / unixcmds / src / grep-2.1 / dfa.c < prev    next >
Encoding:
C/C++ Source or Header  |  1999-10-06  |  65.6 KB  |  2,594 lines

  1. /* dfa.c - deterministic extended regexp routines for GNU
  2.    Copyright (C) 1988 Free Software Foundation, Inc.
  3.  
  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 2, or (at your option)
  7.    any later version.
  8.  
  9.    This program is distributed in the hope that it will be useful,
  10.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12.    GNU General Public License for more details.
  13.  
  14.    You should have received a copy of the GNU General Public License
  15.    along with this program; if not, write to the Free Software
  16.    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA */
  17.  
  18. /* Written June, 1988 by Mike Haertel
  19.    Modified July, 1988 by Arthur David Olson to assist BMG speedups  */
  20.  
  21. #ifdef HAVE_CONFIG_H
  22. #include <config.h>
  23. #endif
  24.  
  25. #include <assert.h>
  26. #include <ctype.h>
  27. #include <stdio.h>
  28.  
  29. #include <sys/types.h>
  30. #ifdef STDC_HEADERS
  31. #include <stdlib.h>
  32. #else
  33. extern char *calloc(), *malloc(), *realloc();
  34. extern void free();
  35. #endif
  36.  
  37. #if defined(HAVE_STRING_H) || defined(STDC_HEADERS)
  38. #include <string.h>
  39. #undef index
  40. #define index strchr
  41. #else
  42. #include <strings.h>
  43. #endif
  44.  
  45. #ifndef DEBUG    /* use the same approach as regex.c */
  46. #undef assert
  47. #define assert(e)
  48. #endif /* DEBUG */
  49.  
  50. #ifndef isgraph
  51. #define isgraph(C) (isprint(C) && !isspace(C))
  52. #endif
  53.  
  54. #if defined (STDC_HEADERS) || (!defined (isascii) && !defined (HAVE_ISASCII))
  55. #define ISALPHA(C) isalpha(C)
  56. #define ISUPPER(C) isupper(C)
  57. #define ISLOWER(C) islower(C)
  58. #define ISDIGIT(C) isdigit(C)
  59. #define ISXDIGIT(C) isxdigit(C)
  60. #define ISSPACE(C) isspace(C)
  61. #define ISPUNCT(C) ispunct(C)
  62. #define ISALNUM(C) isalnum(C)
  63. #define ISPRINT(C) isprint(C)
  64. #define ISGRAPH(C) isgraph(C)
  65. #define ISCNTRL(C) iscntrl(C)
  66. #else
  67. #define ISALPHA(C) (isascii(C) && isalpha(C))
  68. #define ISUPPER(C) (isascii(C) && isupper(C))
  69. #define ISLOWER(C) (isascii(C) && islower(C))
  70. #define ISDIGIT(C) (isascii(C) && isdigit(C))
  71. #define ISXDIGIT(C) (isascii(C) && isxdigit(C))
  72. #define ISSPACE(C) (isascii(C) && isspace(C))
  73. #define ISPUNCT(C) (isascii(C) && ispunct(C))
  74. #define ISALNUM(C) (isascii(C) && isalnum(C))
  75. #define ISPRINT(C) (isascii(C) && isprint(C))
  76. #define ISGRAPH(C) (isascii(C) && isgraph(C))
  77. #define ISCNTRL(C) (isascii(C) && iscntrl(C))
  78. #endif
  79.  
  80. /* If we (don't) have I18N.  */
  81. /* glibc defines _ */
  82. #ifndef _
  83. # ifdef HAVE_LIBINTL_H
  84. #  include <libintl.h>
  85. #  ifndef _
  86. #   define _(Str) gettext (Str)
  87. #  endif
  88. # else
  89. #  define _(Str) (Str)
  90. # endif
  91. #endif
  92.  
  93. #include "regex.h"
  94. #include "dfa.h"
  95.  
  96. static void dfamust PARAMS ((struct dfa *dfa));
  97.  
  98. static ptr_t xcalloc PARAMS ((size_t n, size_t s));
  99. static ptr_t xmalloc PARAMS ((size_t n));
  100. static ptr_t xrealloc PARAMS ((ptr_t p, size_t n));
  101. #ifdef DEBUG
  102. static void prtok PARAMS ((token t));
  103. #endif
  104. static int tstbit PARAMS ((int b, charclass c));
  105. static void setbit PARAMS ((int b, charclass c));
  106. static void clrbit PARAMS ((int b, charclass c));
  107. static void copyset PARAMS ((charclass src, charclass dst));
  108. static void zeroset PARAMS ((charclass s));
  109. static void notset PARAMS ((charclass s));
  110. static int equal PARAMS ((charclass s1, charclass s2));
  111. static int charclass_index PARAMS ((charclass s));
  112. static int looking_at PARAMS ((const char *s));
  113. static token lex PARAMS ((void));
  114. static void addtok PARAMS ((token t));
  115. static void atom PARAMS ((void));
  116. static int nsubtoks PARAMS ((int tindex));
  117. static void copytoks PARAMS ((int tindex, int ntokens));
  118. static void closure PARAMS ((void));
  119. static void branch PARAMS ((void));
  120. static void regexp PARAMS ((int toplevel));
  121. static void copy PARAMS ((position_set *src, position_set *dst));
  122. static void insert PARAMS ((position p, position_set *s));
  123. static void merge PARAMS ((position_set *s1, position_set *s2, position_set *m));
  124. static void delete PARAMS ((position p, position_set *s));
  125. static int state_index PARAMS ((struct dfa *d, position_set *s,
  126.               int newline, int letter));
  127. static void build_state PARAMS ((int s, struct dfa *d));
  128. static void build_state_zero PARAMS ((struct dfa *d));
  129. static char *icatalloc PARAMS ((char *old, char *new));
  130. static char *icpyalloc PARAMS ((char *string));
  131. static char *istrstr PARAMS ((char *lookin, char *lookfor));
  132. static void ifree PARAMS ((char *cp));
  133. static void freelist PARAMS ((char **cpp));
  134. static char **enlist PARAMS ((char **cpp, char *new, size_t len));
  135. static char **comsubs PARAMS ((char *left, char *right));
  136. static char **addlists PARAMS ((char **old, char **new));
  137. static char **inboth PARAMS ((char **left, char **right));
  138.  
  139. static ptr_t
  140. xcalloc(n, s)
  141.      size_t n;
  142.      size_t s;
  143. {
  144.   ptr_t r = calloc(n, s);
  145.  
  146.   if (!r)
  147.     dfaerror(_("Memory exhausted"));
  148.   return r;
  149. }
  150.  
  151. static ptr_t
  152. xmalloc(n)
  153.      size_t n;
  154. {
  155.   ptr_t r = malloc(n);
  156.  
  157.   assert(n != 0);
  158.   if (!r)
  159.     dfaerror(_("Memory exhausted"));
  160.   return r;
  161. }
  162.  
  163. static ptr_t
  164. xrealloc(p, n)
  165.      ptr_t p;
  166.      size_t n;
  167. {
  168.   ptr_t r = realloc(p, n);
  169.  
  170.   assert(n != 0);
  171.   if (!r)
  172.     dfaerror(_("Memory exhausted"));
  173.   return r;
  174. }
  175.  
  176. #define CALLOC(p, t, n) ((p) = (t *) xcalloc((size_t)(n), sizeof (t)))
  177. #define MALLOC(p, t, n) ((p) = (t *) xmalloc((n) * sizeof (t)))
  178. #define REALLOC(p, t, n) ((p) = (t *) xrealloc((ptr_t) (p), (n) * sizeof (t)))
  179.  
  180. /* Reallocate an array of type t if nalloc is too small for index. */
  181. #define REALLOC_IF_NECESSARY(p, t, nalloc, index) \
  182.   if ((index) >= (nalloc))              \
  183.     {                          \
  184.       while ((index) >= (nalloc))          \
  185.     (nalloc) *= 2;                  \
  186.       REALLOC(p, t, nalloc);              \
  187.     }
  188.  
  189. #ifdef DEBUG
  190.  
  191. static void
  192. prtok(t)
  193.      token t;
  194. {
  195.   char *s;
  196.  
  197.   if (t < 0)
  198.     fprintf(stderr, "END");
  199.   else if (t < NOTCHAR)
  200.     fprintf(stderr, "%c", t);
  201.   else
  202.     {
  203.       switch (t)
  204.     {
  205.     case EMPTY: s = "EMPTY"; break;
  206.     case BACKREF: s = "BACKREF"; break;
  207.     case BEGLINE: s = "BEGLINE"; break;
  208.     case ENDLINE: s = "ENDLINE"; break;
  209.     case BEGWORD: s = "BEGWORD"; break;
  210.     case ENDWORD: s = "ENDWORD"; break;
  211.     case LIMWORD: s = "LIMWORD"; break;
  212.     case NOTLIMWORD: s = "NOTLIMWORD"; break;
  213.     case QMARK: s = "QMARK"; break;
  214.     case STAR: s = "STAR"; break;
  215.     case PLUS: s = "PLUS"; break;
  216.     case CAT: s = "CAT"; break;
  217.     case OR: s = "OR"; break;
  218.     case ORTOP: s = "ORTOP"; break;
  219.     case LPAREN: s = "LPAREN"; break;
  220.     case RPAREN: s = "RPAREN"; break;
  221.     default: s = "CSET"; break;
  222.     }
  223.       fprintf(stderr, "%s", s);
  224.     }
  225. }
  226. #endif /* DEBUG */
  227.  
  228. /* Stuff pertaining to charclasses. */
  229.  
  230. static int
  231. tstbit(b, c)
  232.      int b;
  233.      charclass c;
  234. {
  235.   return c[b / INTBITS] & 1 << b % INTBITS;
  236. }
  237.  
  238. static void
  239. setbit(b, c)
  240.      int b;
  241.      charclass c;
  242. {
  243.   c[b / INTBITS] |= 1 << b % INTBITS;
  244. }
  245.  
  246. static void
  247. clrbit(b, c)
  248.      int b;
  249.      charclass c;
  250. {
  251.   c[b / INTBITS] &= ~(1 << b % INTBITS);
  252. }
  253.  
  254. static void
  255. copyset(src, dst)
  256.      charclass src;
  257.      charclass dst;
  258. {
  259.   int i;
  260.  
  261.   for (i = 0; i < CHARCLASS_INTS; ++i)
  262.     dst[i] = src[i];
  263. }
  264.  
  265. static void
  266. zeroset(s)
  267.      charclass s;
  268. {
  269.   int i;
  270.  
  271.   for (i = 0; i < CHARCLASS_INTS; ++i)
  272.     s[i] = 0;
  273. }
  274.  
  275. static void
  276. notset(s)
  277.      charclass s;
  278. {
  279.   int i;
  280.  
  281.   for (i = 0; i < CHARCLASS_INTS; ++i)
  282.     s[i] = ~s[i];
  283. }
  284.  
  285. static int
  286. equal(s1, s2)
  287.      charclass s1;
  288.      charclass s2;
  289. {
  290.   int i;
  291.  
  292.   for (i = 0; i < CHARCLASS_INTS; ++i)
  293.     if (s1[i] != s2[i])
  294.       return 0;
  295.   return 1;
  296. }
  297.  
  298. /* A pointer to the current dfa is kept here during parsing. */
  299. static struct dfa *dfa;
  300.  
  301. /* Find the index of charclass s in dfa->charclasses, or allocate a new charclass. */
  302. static int
  303. charclass_index(s)
  304.      charclass s;
  305. {
  306.   int i;
  307.  
  308.   for (i = 0; i < dfa->cindex; ++i)
  309.     if (equal(s, dfa->charclasses[i]))
  310.       return i;
  311.   REALLOC_IF_NECESSARY(dfa->charclasses, charclass, dfa->calloc, dfa->cindex);
  312.   ++dfa->cindex;
  313.   copyset(s, dfa->charclasses[i]);
  314.   return i;
  315. }
  316.  
  317. /* Syntax bits controlling the behavior of the lexical analyzer. */
  318. static reg_syntax_t syntax_bits, syntax_bits_set;
  319.  
  320. /* Flag for case-folding letters into sets. */
  321. static int case_fold;
  322.  
  323. /* Entry point to set syntax options. */
  324. void
  325. dfasyntax(bits, fold)
  326.      reg_syntax_t bits;
  327.      int fold;
  328. {
  329.   syntax_bits_set = 1;
  330.   syntax_bits = bits;
  331.   case_fold = fold;
  332. }
  333.  
  334. /* Lexical analyzer.  All the dross that deals with the obnoxious
  335.    GNU Regex syntax bits is located here.  The poor, suffering
  336.    reader is referred to the GNU Regex documentation for the
  337.    meaning of the @#%!@#%^!@ syntax bits. */
  338.  
  339. static char *lexstart;        /* Pointer to beginning of input string. */
  340. static char *lexptr;        /* Pointer to next input character. */
  341. static int lexleft;        /* Number of characters remaining. */
  342. static token lasttok;        /* Previous token returned; initially END. */
  343. static int laststart;        /* True if we're separated from beginning or (, |
  344.                    only by zero-width characters. */
  345. static int parens;        /* Count of outstanding left parens. */
  346. static int minrep, maxrep;    /* Repeat counts for {m,n}. */
  347.  
  348. /* Note that characters become unsigned here. */
  349. #define FETCH(c, eoferr)             \
  350.   {                         \
  351.     if (! lexleft)                 \
  352.       if (eoferr != 0)                 \
  353.     dfaerror(eoferr);            \
  354.       else                     \
  355.     return lasttok = END;          \
  356.     (c) = (unsigned char) *lexptr++;  \
  357.     --lexleft;                     \
  358.   }
  359.  
  360. #ifdef __STDC__
  361. #define FUNC(F, P) static int F(int c) { return P(c); }
  362. #else
  363. #define FUNC(F, P) static int F(c) int c; { return P(c); }
  364. #endif
  365.  
  366. FUNC(is_alpha, ISALPHA)
  367. FUNC(is_upper, ISUPPER)
  368. FUNC(is_lower, ISLOWER)
  369. FUNC(is_digit, ISDIGIT)
  370. FUNC(is_xdigit, ISXDIGIT)
  371. FUNC(is_space, ISSPACE)
  372. FUNC(is_punct, ISPUNCT)
  373. FUNC(is_alnum, ISALNUM)
  374. FUNC(is_print, ISPRINT)
  375. FUNC(is_graph, ISGRAPH)
  376. FUNC(is_cntrl, ISCNTRL)
  377.  
  378. static int is_blank(c)
  379. int c;
  380. {
  381.    return (c == ' ' || c == '\t');
  382. }
  383.  
  384. /* The following list maps the names of the Posix named character classes
  385.    to predicate functions that determine whether a given character is in
  386.    the class.  The leading [ has already been eaten by the lexical analyzer. */
  387. static struct {
  388.   const char *name;
  389.   int (*pred) PARAMS ((int));
  390. } prednames[] = {
  391.   { ":alpha:]", is_alpha },
  392.   { ":upper:]", is_upper },
  393.   { ":lower:]", is_lower },
  394.   { ":digit:]", is_digit },
  395.   { ":xdigit:]", is_xdigit },
  396.   { ":space:]", is_space },
  397.   { ":punct:]", is_punct },
  398.   { ":alnum:]", is_alnum },
  399.   { ":print:]", is_print },
  400.   { ":graph:]", is_graph },
  401.   { ":cntrl:]", is_cntrl },
  402.   { ":blank:]", is_blank },
  403.   { 0 }
  404. };
  405.  
  406. static int
  407. looking_at(s)
  408.      const char *s;
  409. {
  410.   size_t len;
  411.  
  412.   len = strlen(s);
  413.   if (lexleft < len)
  414.     return 0;
  415.   return strncmp(s, lexptr, len) == 0;
  416. }
  417.  
  418. static token
  419. lex()
  420. {
  421.   token c, c1, c2;
  422.   int backslash = 0, invert;
  423.   charclass ccl;
  424.   int i;
  425.  
  426.   /* Basic plan: We fetch a character.  If it's a backslash,
  427.      we set the backslash flag and go through the loop again.
  428.      On the plus side, this avoids having a duplicate of the
  429.      main switch inside the backslash case.  On the minus side,
  430.      it means that just about every case begins with
  431.      "if (backslash) ...".  */
  432.   for (i = 0; i < 2; ++i)
  433.     {
  434.       FETCH(c, 0);
  435.       switch (c)
  436.     {
  437.     case '\\':
  438.       if (backslash)
  439.         goto normal_char;
  440.       if (lexleft == 0)
  441.         dfaerror(_("Unfinished \\ escape"));
  442.       backslash = 1;
  443.       break;
  444.  
  445.     case '^':
  446.       if (backslash)
  447.         goto normal_char;
  448.       if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
  449.           || lasttok == END
  450.           || lasttok == LPAREN
  451.           || lasttok == OR)
  452.         return lasttok = BEGLINE;
  453.       goto normal_char;
  454.  
  455.     case '$':
  456.       if (backslash)
  457.         goto normal_char;
  458.       if (syntax_bits & RE_CONTEXT_INDEP_ANCHORS
  459.           || lexleft == 0
  460.           || (syntax_bits & RE_NO_BK_PARENS
  461.           ? lexleft > 0 && *lexptr == ')'
  462.           : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == ')')
  463.           || (syntax_bits & RE_NO_BK_VBAR
  464.           ? lexleft > 0 && *lexptr == '|'
  465.           : lexleft > 1 && lexptr[0] == '\\' && lexptr[1] == '|')
  466.           || ((syntax_bits & RE_NEWLINE_ALT)
  467.               && lexleft > 0 && *lexptr == '\n'))
  468.         return lasttok = ENDLINE;
  469.       goto normal_char;
  470.  
  471.     case '1':
  472.     case '2':
  473.     case '3':
  474.     case '4':
  475.     case '5':
  476.     case '6':
  477.     case '7':
  478.     case '8':
  479.     case '9':
  480.       if (backslash && !(syntax_bits & RE_NO_BK_REFS))
  481.         {
  482.           laststart = 0;
  483.           return lasttok = BACKREF;
  484.         }
  485.       goto normal_char;
  486.  
  487.     case '`':
  488.       if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  489.         return lasttok = BEGLINE;    /* FIXME: should be beginning of string */
  490.       goto normal_char;
  491.  
  492.     case '\'':
  493.       if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  494.         return lasttok = ENDLINE;    /* FIXME: should be end of string */
  495.       goto normal_char;
  496.  
  497.     case '<':
  498.       if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  499.         return lasttok = BEGWORD;
  500.       goto normal_char;
  501.  
  502.     case '>':
  503.       if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  504.         return lasttok = ENDWORD;
  505.       goto normal_char;
  506.  
  507.     case 'b':
  508.       if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  509.         return lasttok = LIMWORD;
  510.       goto normal_char;
  511.  
  512.     case 'B':
  513.       if (backslash && !(syntax_bits & RE_NO_GNU_OPS))
  514.         return lasttok = NOTLIMWORD;
  515.       goto normal_char;
  516.  
  517.     case '?':
  518.       if (syntax_bits & RE_LIMITED_OPS)
  519.         goto normal_char;
  520.       if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
  521.         goto normal_char;
  522.       if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  523.         goto normal_char;
  524.       return lasttok = QMARK;
  525.  
  526.     case '*':
  527.       if (backslash)
  528.         goto normal_char;
  529.       if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  530.         goto normal_char;
  531.       return lasttok = STAR;
  532.  
  533.     case '+':
  534.       if (syntax_bits & RE_LIMITED_OPS)
  535.         goto normal_char;
  536.       if (backslash != ((syntax_bits & RE_BK_PLUS_QM) != 0))
  537.         goto normal_char;
  538.       if (!(syntax_bits & RE_CONTEXT_INDEP_OPS) && laststart)
  539.         goto normal_char;
  540.       return lasttok = PLUS;
  541.  
  542.     case '{':
  543.       if (!(syntax_bits & RE_INTERVALS))
  544.         goto normal_char;
  545.       if (backslash != ((syntax_bits & RE_NO_BK_BRACES) == 0))
  546.         goto normal_char;
  547.       minrep = maxrep = 0;
  548.       /* Cases:
  549.          {M} - exact count
  550.          {M,} - minimum count, maximum is infinity
  551.          {,M} - 0 through M
  552.          {M,N} - M through N */
  553.       FETCH(c, _("unfinished repeat count"));
  554.       if (ISDIGIT(c))
  555.         {
  556.           minrep = c - '0';
  557.           for (;;)
  558.         {
  559.           FETCH(c, _("unfinished repeat count"));
  560.           if (!ISDIGIT(c))
  561.             break;
  562.           minrep = 10 * minrep + c - '0';
  563.         }
  564.         }
  565.       else if (c != ',')
  566.         dfaerror(_("malformed repeat count"));
  567.       if (c == ',')
  568.         for (;;)
  569.           {
  570.         FETCH(c, _("unfinished repeat count"));
  571.         if (!ISDIGIT(c))
  572.           break;
  573.         maxrep = 10 * maxrep + c - '0';
  574.           }
  575.       else
  576.         maxrep = minrep;
  577.       if (!(syntax_bits & RE_NO_BK_BRACES))
  578.         {
  579.           if (c != '\\')
  580.         dfaerror(_("malformed repeat count"));
  581.           FETCH(c, _("unfinished repeat count"));
  582.         }
  583.       if (c != '}')
  584.         dfaerror(_("malformed repeat count"));
  585.       laststart = 0;
  586.       return lasttok = REPMN;
  587.  
  588.     case '|':
  589.       if (syntax_bits & RE_LIMITED_OPS)
  590.         goto normal_char;
  591.       if (backslash != ((syntax_bits & RE_NO_BK_VBAR) == 0))
  592.         goto normal_char;
  593.       laststart = 1;
  594.       return lasttok = OR;
  595.  
  596.     case '\n':
  597.       if (syntax_bits & RE_LIMITED_OPS
  598.           || backslash
  599.           || !(syntax_bits & RE_NEWLINE_ALT))
  600.         goto normal_char;
  601.       laststart = 1;
  602.       return lasttok = OR;
  603.  
  604.     case '(':
  605.       if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
  606.         goto normal_char;
  607.       ++parens;
  608.       laststart = 1;
  609.       return lasttok = LPAREN;
  610.  
  611.     case ')':
  612.       if (backslash != ((syntax_bits & RE_NO_BK_PARENS) == 0))
  613.         goto normal_char;
  614.       if (parens == 0 && syntax_bits & RE_UNMATCHED_RIGHT_PAREN_ORD)
  615.         goto normal_char;
  616.       --parens;
  617.       laststart = 0;
  618.       return lasttok = RPAREN;
  619.  
  620.     case '.':
  621.       if (backslash)
  622.         goto normal_char;
  623.       zeroset(ccl);
  624.       notset(ccl);
  625.       if (!(syntax_bits & RE_DOT_NEWLINE))
  626.         clrbit('\n', ccl);
  627.       if (syntax_bits & RE_DOT_NOT_NULL)
  628.         clrbit('\0', ccl);
  629.       laststart = 0;
  630.       return lasttok = CSET + charclass_index(ccl);
  631.  
  632.     case 'w':
  633.     case 'W':
  634.       if (!backslash || (syntax_bits & RE_NO_GNU_OPS))
  635.         goto normal_char;
  636.       zeroset(ccl);
  637.       for (c2 = 0; c2 < NOTCHAR; ++c2)
  638.         if (ISALNUM(c2))
  639.           setbit(c2, ccl);
  640.       setbit('_', ccl);
  641.       if (c == 'W')
  642.         notset(ccl);
  643.       laststart = 0;
  644.       return lasttok = CSET + charclass_index(ccl);
  645.     
  646.     case '[':
  647.       if (backslash)
  648.         goto normal_char;
  649.       zeroset(ccl);
  650.       FETCH(c, _("Unbalanced ["));
  651.       if (c == '^')
  652.         {
  653.           FETCH(c, _("Unbalanced ["));
  654.           invert = 1;
  655.         }
  656.       else
  657.         invert = 0;
  658.       do
  659.         {
  660.           /* Nobody ever said this had to be fast. :-)
  661.          Note that if we're looking at some other [:...:]
  662.          construct, we just treat it as a bunch of ordinary
  663.          characters.  We can do this because we assume
  664.          regex has checked for syntax errors before
  665.          dfa is ever called. */
  666.           if (c == '[' && (syntax_bits & RE_CHAR_CLASSES))
  667.         for (c1 = 0; prednames[c1].name; ++c1)
  668.           if (looking_at(prednames[c1].name))
  669.             {
  670.             int (*pred)() = prednames[c1].pred;
  671.             if (case_fold
  672.                 && (pred == is_upper || pred == is_lower))
  673.                 pred = is_alpha;
  674.  
  675.               for (c2 = 0; c2 < NOTCHAR; ++c2)
  676.             if ((*pred)(c2))
  677.               setbit(c2, ccl);
  678.               lexptr += strlen(prednames[c1].name);
  679.               lexleft -= strlen(prednames[c1].name);
  680.               FETCH(c1, _("Unbalanced ["));
  681.               goto skip;
  682.             }
  683.           if (c == '\\' && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  684.         FETCH(c, _("Unbalanced ["));
  685.           FETCH(c1, _("Unbalanced ["));
  686.           if (c1 == '-')
  687.         {
  688.           FETCH(c2, _("Unbalanced ["));
  689.           if (c2 == ']')
  690.             {
  691.               /* In the case [x-], the - is an ordinary hyphen,
  692.              which is left in c1, the lookahead character. */
  693.               --lexptr;
  694.               ++lexleft;
  695.               c2 = c;
  696.             }
  697.           else
  698.             {
  699.               if (c2 == '\\'
  700.               && (syntax_bits & RE_BACKSLASH_ESCAPE_IN_LISTS))
  701.             FETCH(c2, _("Unbalanced ["));
  702.               FETCH(c1, _("Unbalanced ["));
  703.             }
  704.         }
  705.           else
  706.         c2 = c;
  707.           while (c <= c2)
  708.         {
  709.           setbit(c, ccl);
  710.           if (case_fold)
  711.             if (ISUPPER(c))
  712.               setbit(tolower(c), ccl);
  713.             else if (ISLOWER(c))
  714.               setbit(toupper(c), ccl);
  715.           ++c;
  716.         }
  717.         skip:
  718.           ;
  719.         }
  720.       while ((c = c1) != ']');
  721.       if (invert)
  722.         {
  723.           notset(ccl);
  724.           if (syntax_bits & RE_HAT_LISTS_NOT_NEWLINE)
  725.         clrbit('\n', ccl);
  726.         }
  727.       laststart = 0;
  728.       return lasttok = CSET + charclass_index(ccl);
  729.  
  730.     default:
  731.     normal_char:
  732.       laststart = 0;
  733.       if (case_fold && ISALPHA(c))
  734.         {
  735.           zeroset(ccl);
  736.           setbit(c, ccl);
  737.           if (isupper(c))
  738.         setbit(tolower(c), ccl);
  739.           else
  740.         setbit(toupper(c), ccl);
  741.           return lasttok = CSET + charclass_index(ccl);
  742.         }
  743.       return c;
  744.     }
  745.     }
  746.  
  747.   /* The above loop should consume at most a backslash
  748.      and some other character. */
  749.   abort();
  750.   return END;    /* keeps pedantic compilers happy. */
  751. }
  752.  
  753. /* Recursive descent parser for regular expressions. */
  754.  
  755. static token tok;        /* Lookahead token. */
  756. static int depth;        /* Current depth of a hypothetical stack
  757.                    holding deferred productions.  This is
  758.                    used to determine the depth that will be
  759.                    required of the real stack later on in
  760.                    dfaanalyze(). */
  761.  
  762. /* Add the given token to the parse tree, maintaining the depth count and
  763.    updating the maximum depth if necessary. */
  764. static void
  765. addtok(t)
  766.      token t;
  767. {
  768.   REALLOC_IF_NECESSARY(dfa->tokens, token, dfa->talloc, dfa->tindex);
  769.   dfa->tokens[dfa->tindex++] = t;
  770.  
  771.   switch (t)
  772.     {
  773.     case QMARK:
  774.     case STAR:
  775.     case PLUS:
  776.       break;
  777.  
  778.     case CAT:
  779.     case OR:
  780.     case ORTOP:
  781.       --depth;
  782.       break;
  783.  
  784.     default:
  785.       ++dfa->nleaves;
  786.     case EMPTY:
  787.       ++depth;
  788.       break;
  789.     }
  790.   if (depth > dfa->depth)
  791.     dfa->depth = depth;
  792. }
  793.  
  794. /* The grammar understood by the parser is as follows.
  795.  
  796.    regexp:
  797.      regexp OR branch
  798.      branch
  799.  
  800.    branch:
  801.      branch closure
  802.      closure
  803.  
  804.    closure:
  805.      closure QMARK
  806.      closure STAR
  807.      closure PLUS
  808.      atom
  809.  
  810.    atom:
  811.      <normal character>
  812.      CSET
  813.      BACKREF
  814.      BEGLINE
  815.      ENDLINE
  816.      BEGWORD
  817.      ENDWORD
  818.      LIMWORD
  819.      NOTLIMWORD
  820.      <empty>
  821.  
  822.    The parser builds a parse tree in postfix form in an array of tokens. */
  823.  
  824. static void
  825. atom()
  826. {
  827.   if ((tok >= 0 && tok < NOTCHAR) || tok >= CSET || tok == BACKREF
  828.       || tok == BEGLINE || tok == ENDLINE || tok == BEGWORD
  829.       || tok == ENDWORD || tok == LIMWORD || tok == NOTLIMWORD)
  830.     {
  831.       addtok(tok);
  832.       tok = lex();
  833.     }
  834.   else if (tok == LPAREN)
  835.     {
  836.       tok = lex();
  837.       regexp(0);
  838.       if (tok != RPAREN)
  839.     dfaerror(_("Unbalanced ("));
  840.       tok = lex();
  841.     }
  842.   else
  843.     addtok(EMPTY);
  844. }
  845.  
  846. /* Return the number of tokens in the given subexpression. */
  847. static int
  848. nsubtoks(tindex)
  849. int tindex;
  850. {
  851.   int ntoks1;
  852.  
  853.   switch (dfa->tokens[tindex - 1])
  854.     {
  855.     default:
  856.       return 1;
  857.     case QMARK:
  858.     case STAR:
  859.     case PLUS:
  860.       return 1 + nsubtoks(tindex - 1);
  861.     case CAT:
  862.     case OR:
  863.     case ORTOP:
  864.       ntoks1 = nsubtoks(tindex - 1);
  865.       return 1 + ntoks1 + nsubtoks(tindex - 1 - ntoks1);
  866.     }
  867. }
  868.  
  869. /* Copy the given subexpression to the top of the tree. */
  870. static void
  871. copytoks(tindex, ntokens)
  872.      int tindex, ntokens;
  873. {
  874.   int i;
  875.  
  876.   for (i = 0; i < ntokens; ++i)
  877.     addtok(dfa->tokens[tindex + i]);
  878. }
  879.  
  880. static void
  881. closure()
  882. {
  883.   int tindex, ntokens, i;
  884.  
  885.   atom();
  886.   while (tok == QMARK || tok == STAR || tok == PLUS || tok == REPMN)
  887.     if (tok == REPMN)
  888.       {
  889.     ntokens = nsubtoks(dfa->tindex);
  890.     tindex = dfa->tindex - ntokens;
  891.     if (maxrep == 0)
  892.       addtok(PLUS);
  893.     if (minrep == 0)
  894.       addtok(QMARK);
  895.     for (i = 1; i < minrep; ++i)
  896.       {
  897.         copytoks(tindex, ntokens);
  898.         addtok(CAT);
  899.       }
  900.     for (; i < maxrep; ++i)
  901.       {
  902.         copytoks(tindex, ntokens);
  903.         addtok(QMARK);
  904.         addtok(CAT);
  905.       }
  906.     tok = lex();
  907.       }
  908.     else
  909.       {
  910.     addtok(tok);
  911.     tok = lex();
  912.       }
  913. }
  914.  
  915. static void
  916. branch()
  917. {
  918.   closure();
  919.   while (tok != RPAREN && tok != OR && tok >= 0)
  920.     {
  921.       closure();
  922.       addtok(CAT);
  923.     }
  924. }
  925.  
  926. static void
  927. regexp(toplevel)
  928.      int toplevel;
  929. {
  930.   branch();
  931.   while (tok == OR)
  932.     {
  933.       tok = lex();
  934.       branch();
  935.       if (toplevel)
  936.     addtok(ORTOP);
  937.       else
  938.     addtok(OR);
  939.     }
  940. }
  941.  
  942. /* Main entry point for the parser.  S is a string to be parsed, len is the
  943.    length of the string, so s can include NUL characters.  D is a pointer to
  944.    the struct dfa to parse into. */
  945. void
  946. dfaparse(s, len, d)
  947.      char *s;
  948.      size_t len;
  949.      struct dfa *d;
  950.  
  951. {
  952.   dfa = d;
  953.   lexstart = lexptr = s;
  954.   lexleft = len;
  955.   lasttok = END;
  956.   laststart = 1;
  957.   parens = 0;
  958.  
  959.   if (! syntax_bits_set)
  960.     dfaerror(_("No syntax specified"));
  961.  
  962.   tok = lex();
  963.   depth = d->depth;
  964.  
  965.   regexp(1);
  966.  
  967.   if (tok != END)
  968.     dfaerror(_("Unbalanced )"));
  969.  
  970.   addtok(END - d->nregexps);
  971.   addtok(CAT);
  972.  
  973.   if (d->nregexps)
  974.     addtok(ORTOP);
  975.  
  976.   ++d->nregexps;
  977. }
  978.  
  979. /* Some primitives for operating on sets of positions. */
  980.  
  981. /* Copy one set to another; the destination must be large enough. */
  982. static void
  983. copy(src, dst)
  984.      position_set *src;
  985.      position_set *dst;
  986. {
  987.   int i;
  988.  
  989.   for (i = 0; i < src->nelem; ++i)
  990.     dst->elems[i] = src->elems[i];
  991.   dst->nelem = src->nelem;
  992. }
  993.  
  994. /* Insert a position in a set.  Position sets are maintained in sorted
  995.    order according to index.  If position already exists in the set with
  996.    the same index then their constraints are logically or'd together.
  997.    S->elems must point to an array large enough to hold the resulting set. */
  998. static void
  999. insert(p, s)
  1000.      position p;
  1001.      position_set *s;
  1002. {
  1003.   int i;
  1004.   position t1, t2;
  1005.  
  1006.   for (i = 0; i < s->nelem && p.index < s->elems[i].index; ++i)
  1007.     continue;
  1008.   if (i < s->nelem && p.index == s->elems[i].index)
  1009.     s->elems[i].constraint |= p.constraint;
  1010.   else
  1011.     {
  1012.       t1 = p;
  1013.       ++s->nelem;
  1014.       while (i < s->nelem)
  1015.     {
  1016.       t2 = s->elems[i];
  1017.       s->elems[i++] = t1;
  1018.       t1 = t2;
  1019.     }
  1020.     }
  1021. }
  1022.  
  1023. /* Merge two sets of positions into a third.  The result is exactly as if
  1024.    the positions of both sets were inserted into an initially empty set. */
  1025. static void
  1026. merge(s1, s2, m)
  1027.      position_set *s1;
  1028.      position_set *s2;
  1029.      position_set *m;
  1030. {
  1031.   int i = 0, j = 0;
  1032.  
  1033.   m->nelem = 0;
  1034.   while (i < s1->nelem && j < s2->nelem)
  1035.     if (s1->elems[i].index > s2->elems[j].index)
  1036.       m->elems[m->nelem++] = s1->elems[i++];
  1037.     else if (s1->elems[i].index < s2->elems[j].index)
  1038.       m->elems[m->nelem++] = s2->elems[j++];
  1039.     else
  1040.       {
  1041.     m->elems[m->nelem] = s1->elems[i++];
  1042.     m->elems[m->nelem++].constraint |= s2->elems[j++].constraint;
  1043.       }
  1044.   while (i < s1->nelem)
  1045.     m->elems[m->nelem++] = s1->elems[i++];
  1046.   while (j < s2->nelem)
  1047.     m->elems[m->nelem++] = s2->elems[j++];
  1048. }
  1049.  
  1050. /* Delete a position from a set. */
  1051. static void
  1052. delete(p, s)
  1053.      position p;
  1054.      position_set *s;
  1055. {
  1056.   int i;
  1057.  
  1058.   for (i = 0; i < s->nelem; ++i)
  1059.     if (p.index == s->elems[i].index)
  1060.       break;
  1061.   if (i < s->nelem)
  1062.     for (--s->nelem; i < s->nelem; ++i)
  1063.       s->elems[i] = s->elems[i + 1];
  1064. }
  1065.  
  1066. /* Find the index of the state corresponding to the given position set with
  1067.    the given preceding context, or create a new state if there is no such
  1068.    state.  Newline and letter tell whether we got here on a newline or
  1069.    letter, respectively. */
  1070. static int
  1071. state_index(d, s, newline, letter)
  1072.      struct dfa *d;
  1073.      position_set *s;
  1074.      int newline;
  1075.      int letter;
  1076. {
  1077.   int hash = 0;
  1078.   int constraint;
  1079.   int i, j;
  1080.  
  1081.   newline = newline ? 1 : 0;
  1082.   letter = letter ? 1 : 0;
  1083.  
  1084.   for (i = 0; i < s->nelem; ++i)
  1085.     hash ^= s->elems[i].index + s->elems[i].constraint;
  1086.  
  1087.   /* Try to find a state that exactly matches the proposed one. */
  1088.   for (i = 0; i < d->sindex; ++i)
  1089.     {
  1090.       if (hash != d->states[i].hash || s->nelem != d->states[i].elems.nelem
  1091.       || newline != d->states[i].newline || letter != d->states[i].letter)
  1092.     continue;
  1093.       for (j = 0; j < s->nelem; ++j)
  1094.     if (s->elems[j].constraint
  1095.         != d->states[i].elems.elems[j].constraint
  1096.         || s->elems[j].index != d->states[i].elems.elems[j].index)
  1097.       break;
  1098.       if (j == s->nelem)
  1099.     return i;
  1100.     }
  1101.  
  1102.   /* We'll have to create a new state. */
  1103.   REALLOC_IF_NECESSARY(d->states, dfa_state, d->salloc, d->sindex);
  1104.   d->states[i].hash = hash;
  1105.   MALLOC(d->states[i].elems.elems, position, s->nelem);
  1106.   copy(s, &d->states[i].elems);
  1107.   d->states[i].newline = newline;
  1108.   d->states[i].letter = letter;
  1109.   d->states[i].backref = 0;
  1110.   d->states[i].constraint = 0;
  1111.   d->states[i].first_end = 0;
  1112.   for (j = 0; j < s->nelem; ++j)
  1113.     if (d->tokens[s->elems[j].index] < 0)
  1114.       {
  1115.     constraint = s->elems[j].constraint;
  1116.     if (SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 0)
  1117.         || SUCCEEDS_IN_CONTEXT(constraint, newline, 0, letter, 1)
  1118.         || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 0)
  1119.         || SUCCEEDS_IN_CONTEXT(constraint, newline, 1, letter, 1))
  1120.       d->states[i].constraint |= constraint;
  1121.     if (! d->states[i].first_end)
  1122.       d->states[i].first_end = d->tokens[s->elems[j].index];
  1123.       }
  1124.     else if (d->tokens[s->elems[j].index] == BACKREF)
  1125.       {
  1126.     d->states[i].constraint = NO_CONSTRAINT;
  1127.     d->states[i].backref = 1;
  1128.       }
  1129.  
  1130.   ++d->sindex;
  1131.  
  1132.   return i;
  1133. }
  1134.  
  1135. /* Find the epsilon closure of a set of positions.  If any position of the set
  1136.    contains a symbol that matches the empty string in some context, replace
  1137.    that position with the elements of its follow labeled with an appropriate
  1138.    constraint.  Repeat exhaustively until no funny positions are left.
  1139.    S->elems must be large enough to hold the result. */
  1140. static void epsclosure PARAMS ((position_set *s, struct dfa *d));
  1141.  
  1142. static void
  1143. epsclosure(s, d)
  1144.      position_set *s;
  1145.      struct dfa *d;
  1146. {
  1147.   int i, j;
  1148.   int *visited;
  1149.   position p, old;
  1150.  
  1151.   MALLOC(visited, int, d->tindex);
  1152.   for (i = 0; i < d->tindex; ++i)
  1153.     visited[i] = 0;
  1154.  
  1155.   for (i = 0; i < s->nelem; ++i)
  1156.     if (d->tokens[s->elems[i].index] >= NOTCHAR
  1157.     && d->tokens[s->elems[i].index] != BACKREF
  1158.     && d->tokens[s->elems[i].index] < CSET)
  1159.       {
  1160.     old = s->elems[i];
  1161.     p.constraint = old.constraint;
  1162.     delete(s->elems[i], s);
  1163.     if (visited[old.index])
  1164.       {
  1165.         --i;
  1166.         continue;
  1167.       }
  1168.     visited[old.index] = 1;
  1169.     switch (d->tokens[old.index])
  1170.       {
  1171.       case BEGLINE:
  1172.         p.constraint &= BEGLINE_CONSTRAINT;
  1173.         break;
  1174.       case ENDLINE:
  1175.         p.constraint &= ENDLINE_CONSTRAINT;
  1176.         break;
  1177.       case BEGWORD:
  1178.         p.constraint &= BEGWORD_CONSTRAINT;
  1179.         break;
  1180.       case ENDWORD:
  1181.         p.constraint &= ENDWORD_CONSTRAINT;
  1182.         break;
  1183.       case LIMWORD:
  1184.         p.constraint &= LIMWORD_CONSTRAINT;
  1185.         break;
  1186.       case NOTLIMWORD:
  1187.         p.constraint &= NOTLIMWORD_CONSTRAINT;
  1188.         break;
  1189.       default:
  1190.         break;
  1191.       }
  1192.     for (j = 0; j < d->follows[old.index].nelem; ++j)
  1193.       {
  1194.         p.index = d->follows[old.index].elems[j].index;
  1195.         insert(p, s);
  1196.       }
  1197.     /* Force rescan to start at the beginning. */
  1198.     i = -1;
  1199.       }
  1200.  
  1201.   free(visited);
  1202. }
  1203.  
  1204. /* Perform bottom-up analysis on the parse tree, computing various functions.
  1205.    Note that at this point, we're pretending constructs like \< are real
  1206.    characters rather than constraints on what can follow them.
  1207.  
  1208.    Nullable:  A node is nullable if it is at the root of a regexp that can
  1209.    match the empty string.
  1210.    *  EMPTY leaves are nullable.
  1211.    * No other leaf is nullable.
  1212.    * A QMARK or STAR node is nullable.
  1213.    * A PLUS node is nullable if its argument is nullable.
  1214.    * A CAT node is nullable if both its arguments are nullable.
  1215.    * An OR node is nullable if either argument is nullable.
  1216.  
  1217.    Firstpos:  The firstpos of a node is the set of positions (nonempty leaves)
  1218.    that could correspond to the first character of a string matching the
  1219.    regexp rooted at the given node.
  1220.    * EMPTY leaves have empty firstpos.
  1221.    * The firstpos of a nonempty leaf is that leaf itself.
  1222.    * The firstpos of a QMARK, STAR, or PLUS node is the firstpos of its
  1223.      argument.
  1224.    * The firstpos of a CAT node is the firstpos of the left argument, union
  1225.      the firstpos of the right if the left argument is nullable.
  1226.    * The firstpos of an OR node is the union of firstpos of each argument.
  1227.  
  1228.    Lastpos:  The lastpos of a node is the set of positions that could
  1229.    correspond to the last character of a string matching the regexp at
  1230.    the given node.
  1231.    * EMPTY leaves have empty lastpos.
  1232.    * The lastpos of a nonempty leaf is that leaf itself.
  1233.    * The lastpos of a QMARK, STAR, or PLUS node is the lastpos of its
  1234.      argument.
  1235.    * The lastpos of a CAT node is the lastpos of its right argument, union
  1236.      the lastpos of the left if the right argument is nullable.
  1237.    * The lastpos of an OR node is the union of the lastpos of each argument.
  1238.  
  1239.    Follow:  The follow of a position is the set of positions that could
  1240.    correspond to the character following a character matching the node in
  1241.    a string matching the regexp.  At this point we consider special symbols
  1242.    that match the empty string in some context to be just normal characters.
  1243.    Later, if we find that a special symbol is in a follow set, we will
  1244.    replace it with the elements of its follow, labeled with an appropriate
  1245.    constraint.
  1246.    * Every node in the firstpos of the argument of a STAR or PLUS node is in
  1247.      the follow of every node in the lastpos.
  1248.    * Every node in the firstpos of the second argument of a CAT node is in
  1249.      the follow of every node in the lastpos of the first argument.
  1250.  
  1251.    Because of the postfix representation of the parse tree, the depth-first
  1252.    analysis is conveniently done by a linear scan with the aid of a stack.
  1253.    Sets are stored as arrays of the elements, obeying a stack-like allocation
  1254.    scheme; the number of elements in each set deeper in the stack can be
  1255.    used to determine the address of a particular set's array. */
  1256. void
  1257. dfaanalyze(d, searchflag)
  1258.      struct dfa *d;
  1259.      int searchflag;
  1260. {
  1261.   int *nullable;        /* Nullable stack. */
  1262.   int *nfirstpos;        /* Element count stack for firstpos sets. */
  1263.   position *firstpos;        /* Array where firstpos elements are stored. */
  1264.   int *nlastpos;        /* Element count stack for lastpos sets. */
  1265.   position *lastpos;        /* Array where lastpos elements are stored. */
  1266.   int *nalloc;            /* Sizes of arrays allocated to follow sets. */
  1267.   position_set tmp;        /* Temporary set for merging sets. */
  1268.   position_set merged;        /* Result of merging sets. */
  1269.   int wants_newline;        /* True if some position wants newline info. */
  1270.   int *o_nullable;
  1271.   int *o_nfirst, *o_nlast;
  1272.   position *o_firstpos, *o_lastpos;
  1273.   int i, j;
  1274.   position *pos;
  1275.  
  1276. #ifdef DEBUG
  1277.   fprintf(stderr, "dfaanalyze:\n");
  1278.   for (i = 0; i < d->tindex; ++i)
  1279.     {
  1280.       fprintf(stderr, " %d:", i);
  1281.       prtok(d->tokens[i]);
  1282.     }
  1283.   putc('\n', stderr);
  1284. #endif
  1285.  
  1286.   d->searchflag = searchflag;
  1287.  
  1288.   MALLOC(nullable, int, d->depth);
  1289.   o_nullable = nullable;
  1290.   MALLOC(nfirstpos, int, d->depth);
  1291.   o_nfirst = nfirstpos;
  1292.   MALLOC(firstpos, position, d->nleaves);
  1293.   o_firstpos = firstpos, firstpos += d->nleaves;
  1294.   MALLOC(nlastpos, int, d->depth);
  1295.   o_nlast = nlastpos;
  1296.   MALLOC(lastpos, position, d->nleaves);
  1297.   o_lastpos = lastpos, lastpos += d->nleaves;
  1298.   MALLOC(nalloc, int, d->tindex);
  1299.   for (i = 0; i < d->tindex; ++i)
  1300.     nalloc[i] = 0;
  1301.   MALLOC(merged.elems, position, d->nleaves);
  1302.  
  1303.   CALLOC(d->follows, position_set, d->tindex);
  1304.  
  1305.   for (i = 0; i < d->tindex; ++i)
  1306. #ifdef DEBUG
  1307.     {                /* Nonsyntactic #ifdef goo... */
  1308. #endif
  1309.     switch (d->tokens[i])
  1310.       {
  1311.       case EMPTY:
  1312.     /* The empty set is nullable. */
  1313.     *nullable++ = 1;
  1314.  
  1315.     /* The firstpos and lastpos of the empty leaf are both empty. */
  1316.     *nfirstpos++ = *nlastpos++ = 0;
  1317.     break;
  1318.  
  1319.       case STAR:
  1320.       case PLUS:
  1321.     /* Every element in the firstpos of the argument is in the follow
  1322.        of every element in the lastpos. */
  1323.     tmp.nelem = nfirstpos[-1];
  1324.     tmp.elems = firstpos;
  1325.     pos = lastpos;
  1326.     for (j = 0; j < nlastpos[-1]; ++j)
  1327.       {
  1328.         merge(&tmp, &d->follows[pos[j].index], &merged);
  1329.         REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
  1330.                  nalloc[pos[j].index], merged.nelem - 1);
  1331.         copy(&merged, &d->follows[pos[j].index]);
  1332.       }
  1333.  
  1334.       case QMARK:
  1335.     /* A QMARK or STAR node is automatically nullable. */
  1336.     if (d->tokens[i] != PLUS)
  1337.       nullable[-1] = 1;
  1338.     break;
  1339.  
  1340.       case CAT:
  1341.     /* Every element in the firstpos of the second argument is in the
  1342.        follow of every element in the lastpos of the first argument. */
  1343.     tmp.nelem = nfirstpos[-1];
  1344.     tmp.elems = firstpos;
  1345.     pos = lastpos + nlastpos[-1];
  1346.     for (j = 0; j < nlastpos[-2]; ++j)
  1347.       {
  1348.         merge(&tmp, &d->follows[pos[j].index], &merged);
  1349.         REALLOC_IF_NECESSARY(d->follows[pos[j].index].elems, position,
  1350.                  nalloc[pos[j].index], merged.nelem - 1);
  1351.         copy(&merged, &d->follows[pos[j].index]);
  1352.       }
  1353.  
  1354.     /* The firstpos of a CAT node is the firstpos of the first argument,
  1355.        union that of the second argument if the first is nullable. */
  1356.     if (nullable[-2])
  1357.       nfirstpos[-2] += nfirstpos[-1];
  1358.     else
  1359.       firstpos += nfirstpos[-1];
  1360.     --nfirstpos;
  1361.  
  1362.     /* The lastpos of a CAT node is the lastpos of the second argument,
  1363.        union that of the first argument if the second is nullable. */
  1364.     if (nullable[-1])
  1365.       nlastpos[-2] += nlastpos[-1];
  1366.     else
  1367.       {
  1368.         pos = lastpos + nlastpos[-2];
  1369.         for (j = nlastpos[-1] - 1; j >= 0; --j)
  1370.           pos[j] = lastpos[j];
  1371.         lastpos += nlastpos[-2];
  1372.         nlastpos[-2] = nlastpos[-1];
  1373.       }
  1374.     --nlastpos;
  1375.  
  1376.     /* A CAT node is nullable if both arguments are nullable. */
  1377.     nullable[-2] = nullable[-1] && nullable[-2];
  1378.     --nullable;
  1379.     break;
  1380.  
  1381.       case OR:
  1382.       case ORTOP:
  1383.     /* The firstpos is the union of the firstpos of each argument. */
  1384.     nfirstpos[-2] += nfirstpos[-1];
  1385.     --nfirstpos;
  1386.  
  1387.     /* The lastpos is the union of the lastpos of each argument. */
  1388.     nlastpos[-2] += nlastpos[-1];
  1389.     --nlastpos;
  1390.  
  1391.     /* An OR node is nullable if either argument is nullable. */
  1392.     nullable[-2] = nullable[-1] || nullable[-2];
  1393.     --nullable;
  1394.     break;
  1395.  
  1396.       default:
  1397.     /* Anything else is a nonempty position.  (Note that special
  1398.        constructs like \< are treated as nonempty strings here;
  1399.        an "epsilon closure" effectively makes them nullable later.
  1400.        Backreferences have to get a real position so we can detect
  1401.        transitions on them later.  But they are nullable. */
  1402.     *nullable++ = d->tokens[i] == BACKREF;
  1403.  
  1404.     /* This position is in its own firstpos and lastpos. */
  1405.     *nfirstpos++ = *nlastpos++ = 1;
  1406.     --firstpos, --lastpos;
  1407.     firstpos->index = lastpos->index = i;
  1408.     firstpos->constraint = lastpos->constraint = NO_CONSTRAINT;
  1409.  
  1410.     /* Allocate the follow set for this position. */
  1411.     nalloc[i] = 1;
  1412.     MALLOC(d->follows[i].elems, position, nalloc[i]);
  1413.     break;
  1414.       }
  1415. #ifdef DEBUG
  1416.     /* ... balance the above nonsyntactic #ifdef goo... */
  1417.       fprintf(stderr, "node %d:", i);
  1418.       prtok(d->tokens[i]);
  1419.       putc('\n', stderr);
  1420.       fprintf(stderr, nullable[-1] ? " nullable: yes\n" : " nullable: no\n");
  1421.       fprintf(stderr, " firstpos:");
  1422.       for (j = nfirstpos[-1] - 1; j >= 0; --j)
  1423.     {
  1424.       fprintf(stderr, " %d:", firstpos[j].index);
  1425.       prtok(d->tokens[firstpos[j].index]);
  1426.     }
  1427.       fprintf(stderr, "\n lastpos:");
  1428.       for (j = nlastpos[-1] - 1; j >= 0; --j)
  1429.     {
  1430.       fprintf(stderr, " %d:", lastpos[j].index);
  1431.       prtok(d->tokens[lastpos[j].index]);
  1432.     }
  1433.       putc('\n', stderr);
  1434.     }
  1435. #endif
  1436.  
  1437.   /* For each follow set that is the follow set of a real position, replace
  1438.      it with its epsilon closure. */
  1439.   for (i = 0; i < d->tindex; ++i)
  1440.     if (d->tokens[i] < NOTCHAR || d->tokens[i] == BACKREF
  1441.     || d->tokens[i] >= CSET)
  1442.       {
  1443. #ifdef DEBUG
  1444.     fprintf(stderr, "follows(%d:", i);
  1445.     prtok(d->tokens[i]);
  1446.     fprintf(stderr, "):");
  1447.     for (j = d->follows[i].nelem - 1; j >= 0; --j)
  1448.       {
  1449.         fprintf(stderr, " %d:", d->follows[i].elems[j].index);
  1450.         prtok(d->tokens[d->follows[i].elems[j].index]);
  1451.       }
  1452.     putc('\n', stderr);
  1453. #endif
  1454.     copy(&d->follows[i], &merged);
  1455.     epsclosure(&merged, d);
  1456.     if (d->follows[i].nelem < merged.nelem)
  1457.       REALLOC(d->follows[i].elems, position, merged.nelem);
  1458.     copy(&merged, &d->follows[i]);
  1459.       }
  1460.  
  1461.   /* Get the epsilon closure of the firstpos of the regexp.  The result will
  1462.      be the set of positions of state 0. */
  1463.   merged.nelem = 0;
  1464.   for (i = 0; i < nfirstpos[-1]; ++i)
  1465.     insert(firstpos[i], &merged);
  1466.   epsclosure(&merged, d);
  1467.  
  1468.   /* Check if any of the positions of state 0 will want newline context. */
  1469.   wants_newline = 0;
  1470.   for (i = 0; i < merged.nelem; ++i)
  1471.     if (PREV_NEWLINE_DEPENDENT(merged.elems[i].constraint))
  1472.       wants_newline = 1;
  1473.  
  1474.   /* Build the initial state. */
  1475.   d->salloc = 1;
  1476.   d->sindex = 0;
  1477.   MALLOC(d->states, dfa_state, d->salloc);
  1478.   state_index(d, &merged, wants_newline, 0);
  1479.  
  1480.   free(o_nullable);
  1481.   free(o_nfirst);
  1482.   free(o_firstpos);
  1483.   free(o_nlast);
  1484.   free(o_lastpos);
  1485.   free(nalloc);
  1486.   free(merged.elems);
  1487. }
  1488.  
  1489. /* Find, for each character, the transition out of state s of d, and store
  1490.    it in the appropriate slot of trans.
  1491.  
  1492.    We divide the positions of s into groups (positions can appear in more
  1493.    than one group).  Each group is labeled with a set of characters that
  1494.    every position in the group matches (taking into account, if necessary,
  1495.    preceding context information of s).  For each group, find the union
  1496.    of the its elements' follows.  This set is the set of positions of the
  1497.    new state.  For each character in the group's label, set the transition
  1498.    on this character to be to a state corresponding to the set's positions,
  1499.    and its associated backward context information, if necessary.
  1500.  
  1501.    If we are building a searching matcher, we include the positions of state
  1502.    0 in every state.
  1503.  
  1504.    The collection of groups is constructed by building an equivalence-class
  1505.    partition of the positions of s.
  1506.  
  1507.    For each position, find the set of characters C that it matches.  Eliminate
  1508.    any characters from C that fail on grounds of backward context.
  1509.  
  1510.    Search through the groups, looking for a group whose label L has nonempty
  1511.    intersection with C.  If L - C is nonempty, create a new group labeled
  1512.    L - C and having the same positions as the current group, and set L to
  1513.    the intersection of L and C.  Insert the position in this group, set
  1514.    C = C - L, and resume scanning.
  1515.  
  1516.    If after comparing with every group there are characters remaining in C,
  1517.    create a new group labeled with the characters of C and insert this
  1518.    position in that group. */
  1519. void
  1520. dfastate(s, d, trans)
  1521.      int s;
  1522.      struct dfa *d;
  1523.      int trans[];
  1524. {
  1525.   position_set grps[NOTCHAR];    /* As many as will ever be needed. */
  1526.   charclass labels[NOTCHAR];    /* Labels corresponding to the groups. */
  1527.   int ngrps = 0;        /* Number of groups actually used. */
  1528.   position pos;            /* Current position being considered. */
  1529.   charclass matches;        /* Set of matching characters. */
  1530.   int matchesf;            /* True if matches is nonempty. */
  1531.   charclass intersect;        /* Intersection with some label set. */
  1532.   int intersectf;        /* True if intersect is nonempty. */
  1533.   charclass leftovers;        /* Stuff in the label that didn't match. */
  1534.   int leftoversf;        /* True if leftovers is nonempty. */
  1535.   static charclass letters;    /* Set of characters considered letters. */
  1536.   static charclass newline;    /* Set of characters that aren't newline. */
  1537.   position_set follows;        /* Union of the follows of some group. */
  1538.   position_set tmp;        /* Temporary space for merging sets. */
  1539.   int state;            /* New state. */
  1540.   int wants_newline;        /* New state wants to know newline context. */
  1541.   int state_newline;        /* New state on a newline transition. */
  1542.   int wants_letter;        /* New state wants to know letter context. */
  1543.   int state_letter;        /* New state on a letter transition. */
  1544.   static int initialized;    /* Flag for static initialization. */
  1545.   int i, j, k;
  1546.  
  1547.   /* Initialize the set of letters, if necessary. */
  1548.   if (! initialized)
  1549.     {
  1550.       initialized = 1;
  1551.       for (i = 0; i < NOTCHAR; ++i)
  1552.     if (ISALNUM(i))
  1553.       setbit(i, letters);
  1554.       setbit('\n', newline);
  1555.     }
  1556.  
  1557.   zeroset(matches);
  1558.  
  1559.   for (i = 0; i < d->states[s].elems.nelem; ++i)
  1560.     {
  1561.       pos = d->states[s].elems.elems[i];
  1562.       if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR)
  1563.     setbit(d->tokens[pos.index], matches);
  1564.       else if (d->tokens[pos.index] >= CSET)
  1565.     copyset(d->charclasses[d->tokens[pos.index] - CSET], matches);
  1566.       else
  1567.     continue;
  1568.  
  1569.       /* Some characters may need to be eliminated from matches because
  1570.      they fail in the current context. */
  1571.       if (pos.constraint != 0xFF)
  1572.     {
  1573.       if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1574.                      d->states[s].newline, 1))
  1575.         clrbit('\n', matches);
  1576.       if (! MATCHES_NEWLINE_CONTEXT(pos.constraint,
  1577.                      d->states[s].newline, 0))
  1578.         for (j = 0; j < CHARCLASS_INTS; ++j)
  1579.           matches[j] &= newline[j];
  1580.       if (! MATCHES_LETTER_CONTEXT(pos.constraint,
  1581.                     d->states[s].letter, 1))
  1582.         for (j = 0; j < CHARCLASS_INTS; ++j)
  1583.           matches[j] &= ~letters[j];
  1584.       if (! MATCHES_LETTER_CONTEXT(pos.constraint,
  1585.                     d->states[s].letter, 0))
  1586.         for (j = 0; j < CHARCLASS_INTS; ++j)
  1587.           matches[j] &= letters[j];
  1588.  
  1589.       /* If there are no characters left, there's no point in going on. */
  1590.       for (j = 0; j < CHARCLASS_INTS && !matches[j]; ++j)
  1591.         continue;
  1592.       if (j == CHARCLASS_INTS)
  1593.         continue;
  1594.     }
  1595.  
  1596.       for (j = 0; j < ngrps; ++j)
  1597.     {
  1598.       /* If matches contains a single character only, and the current
  1599.          group's label doesn't contain that character, go on to the
  1600.          next group. */
  1601.       if (d->tokens[pos.index] >= 0 && d->tokens[pos.index] < NOTCHAR
  1602.           && !tstbit(d->tokens[pos.index], labels[j]))
  1603.         continue;
  1604.  
  1605.       /* Check if this group's label has a nonempty intersection with
  1606.          matches. */
  1607.       intersectf = 0;
  1608.       for (k = 0; k < CHARCLASS_INTS; ++k)
  1609.         (intersect[k] = matches[k] & labels[j][k]) ? (intersectf = 1) : 0;
  1610.       if (! intersectf)
  1611.         continue;
  1612.  
  1613.       /* It does; now find the set differences both ways. */
  1614.       leftoversf = matchesf = 0;
  1615.       for (k = 0; k < CHARCLASS_INTS; ++k)
  1616.         {
  1617.           /* Even an optimizing compiler can't know this for sure. */
  1618.           int match = matches[k], label = labels[j][k];
  1619.  
  1620.           (leftovers[k] = ~match & label) ? (leftoversf = 1) : 0;
  1621.           (matches[k] = match & ~label) ? (matchesf = 1) : 0;
  1622.         }
  1623.  
  1624.       /* If there were leftovers, create a new group labeled with them. */
  1625.       if (leftoversf)
  1626.         {
  1627.           copyset(leftovers, labels[ngrps]);
  1628.           copyset(intersect, labels[j]);
  1629.           MALLOC(grps[ngrps].elems, position, d->nleaves);
  1630.           copy(&grps[j], &grps[ngrps]);
  1631.           ++ngrps;
  1632.         }
  1633.  
  1634.       /* Put the position in the current group.  Note that there is no
  1635.          reason to call insert() here. */
  1636.       grps[j].elems[grps[j].nelem++] = pos;
  1637.  
  1638.       /* If every character matching the current position has been
  1639.          accounted for, we're done. */
  1640.       if (! matchesf)
  1641.         break;
  1642.     }
  1643.  
  1644.       /* If we've passed the last group, and there are still characters
  1645.      unaccounted for, then we'll have to create a new group. */
  1646.       if (j == ngrps)
  1647.     {
  1648.       copyset(matches, labels[ngrps]);
  1649.       zeroset(matches);
  1650.       MALLOC(grps[ngrps].elems, position, d->nleaves);
  1651.       grps[ngrps].nelem = 1;
  1652.       grps[ngrps].elems[0] = pos;
  1653.       ++ngrps;
  1654.     }
  1655.     }
  1656.  
  1657.   MALLOC(follows.elems, position, d->nleaves);
  1658.   MALLOC(tmp.elems, position, d->nleaves);
  1659.  
  1660.   /* If we are a searching matcher, the default transition is to a state
  1661.      containing the positions of state 0, otherwise the default transition
  1662.      is to fail miserably. */
  1663.   if (d->searchflag)
  1664.     {
  1665.       wants_newline = 0;
  1666.       wants_letter = 0;
  1667.       for (i = 0; i < d->states[0].elems.nelem; ++i)
  1668.     {
  1669.       if (PREV_NEWLINE_DEPENDENT(d->states[0].elems.elems[i].constraint))
  1670.         wants_newline = 1;
  1671.       if (PREV_LETTER_DEPENDENT(d->states[0].elems.elems[i].constraint))
  1672.         wants_letter = 1;
  1673.     }
  1674.       copy(&d->states[0].elems, &follows);
  1675.       state = state_index(d, &follows, 0, 0);
  1676.       if (wants_newline)
  1677.     state_newline = state_index(d, &follows, 1, 0);
  1678.       else
  1679.     state_newline = state;
  1680.       if (wants_letter)
  1681.     state_letter = state_index(d, &follows, 0, 1);
  1682.       else
  1683.     state_letter = state;
  1684.       for (i = 0; i < NOTCHAR; ++i)
  1685.     trans[i] = (ISALNUM(i)) ? state_letter : state;
  1686.       trans['\n'] = state_newline;
  1687.     }
  1688.   else
  1689.     for (i = 0; i < NOTCHAR; ++i)
  1690.       trans[i] = -1;
  1691.  
  1692.   for (i = 0; i < ngrps; ++i)
  1693.     {
  1694.       follows.nelem = 0;
  1695.  
  1696.       /* Find the union of the follows of the positions of the group.
  1697.      This is a hideously inefficient loop.  Fix it someday. */
  1698.       for (j = 0; j < grps[i].nelem; ++j)
  1699.     for (k = 0; k < d->follows[grps[i].elems[j].index].nelem; ++k)
  1700.       insert(d->follows[grps[i].elems[j].index].elems[k], &follows);
  1701.  
  1702.       /* If we are building a searching matcher, throw in the positions
  1703.      of state 0 as well. */
  1704.       if (d->searchflag)
  1705.     for (j = 0; j < d->states[0].elems.nelem; ++j)
  1706.       insert(d->states[0].elems.elems[j], &follows);
  1707.  
  1708.       /* Find out if the new state will want any context information. */
  1709.       wants_newline = 0;
  1710.       if (tstbit('\n', labels[i]))
  1711.     for (j = 0; j < follows.nelem; ++j)
  1712.       if (PREV_NEWLINE_DEPENDENT(follows.elems[j].constraint))
  1713.         wants_newline = 1;
  1714.  
  1715.       wants_letter = 0;
  1716.       for (j = 0; j < CHARCLASS_INTS; ++j)
  1717.     if (labels[i][j] & letters[j])
  1718.       break;
  1719.       if (j < CHARCLASS_INTS)
  1720.     for (j = 0; j < follows.nelem; ++j)
  1721.       if (PREV_LETTER_DEPENDENT(follows.elems[j].constraint))
  1722.         wants_letter = 1;
  1723.  
  1724.       /* Find the state(s) corresponding to the union of the follows. */
  1725.       state = state_index(d, &follows, 0, 0);
  1726.       if (wants_newline)
  1727.     state_newline = state_index(d, &follows, 1, 0);
  1728.       else
  1729.     state_newline = state;
  1730.       if (wants_letter)
  1731.     state_letter = state_index(d, &follows, 0, 1);
  1732.       else
  1733.     state_letter = state;
  1734.  
  1735.       /* Set the transitions for each character in the current label. */
  1736.       for (j = 0; j < CHARCLASS_INTS; ++j)
  1737.     for (k = 0; k < INTBITS; ++k)
  1738.       if (labels[i][j] & 1 << k)
  1739.         {
  1740.           int c = j * INTBITS + k;
  1741.  
  1742.           if (c == '\n')
  1743.         trans[c] = state_newline;
  1744.           else if (ISALNUM(c))
  1745.         trans[c] = state_letter;
  1746.           else if (c < NOTCHAR)
  1747.         trans[c] = state;
  1748.         }
  1749.     }
  1750.  
  1751.   for (i = 0; i < ngrps; ++i)
  1752.     free(grps[i].elems);
  1753.   free(follows.elems);
  1754.   free(tmp.elems);
  1755. }
  1756.  
  1757. /* Some routines for manipulating a compiled dfa's transition tables.
  1758.    Each state may or may not have a transition table; if it does, and it
  1759.    is a non-accepting state, then d->trans[state] points to its table.
  1760.    If it is an accepting state then d->fails[state] points to its table.
  1761.    If it has no table at all, then d->trans[state] is NULL.
  1762.    TODO: Improve this comment, get rid of the unnecessary redundancy. */
  1763.  
  1764. static void
  1765. build_state(s, d)
  1766.      int s;
  1767.      struct dfa *d;
  1768. {
  1769.   int *trans;            /* The new transition table. */
  1770.   int i;
  1771.  
  1772.   /* Set an upper limit on the number of transition tables that will ever
  1773.      exist at once.  1024 is arbitrary.  The idea is that the frequently
  1774.      used transition tables will be quickly rebuilt, whereas the ones that
  1775.      were only needed once or twice will be cleared away. */
  1776.   if (d->trcount >= 1024)
  1777.     {
  1778.       for (i = 0; i < d->tralloc; ++i)
  1779.     if (d->trans[i])
  1780.       {
  1781.         free((ptr_t) d->trans[i]);
  1782.         d->trans[i] = NULL;
  1783.       }
  1784.     else if (d->fails[i])
  1785.       {
  1786.         free((ptr_t) d->fails[i]);
  1787.         d->fails[i] = NULL;
  1788.       }
  1789.       d->trcount = 0;
  1790.     }
  1791.  
  1792.   ++d->trcount;
  1793.  
  1794.   /* Set up the success bits for this state. */
  1795.   d->success[s] = 0;
  1796.   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 1, d->states[s].letter, 0,
  1797.       s, *d))
  1798.     d->success[s] |= 4;
  1799.   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 1,
  1800.       s, *d))
  1801.     d->success[s] |= 2;
  1802.   if (ACCEPTS_IN_CONTEXT(d->states[s].newline, 0, d->states[s].letter, 0,
  1803.       s, *d))
  1804.     d->success[s] |= 1;
  1805.  
  1806.   MALLOC(trans, int, NOTCHAR);
  1807.   dfastate(s, d, trans);
  1808.  
  1809.   /* Now go through the new transition table, and make sure that the trans
  1810.      and fail arrays are allocated large enough to hold a pointer for the
  1811.      largest state mentioned in the table. */
  1812.   for (i = 0; i < NOTCHAR; ++i)
  1813.     if (trans[i] >= d->tralloc)
  1814.       {
  1815.     int oldalloc = d->tralloc;
  1816.  
  1817.     while (trans[i] >= d->tralloc)
  1818.       d->tralloc *= 2;
  1819.     REALLOC(d->realtrans, int *, d->tralloc + 1);
  1820.     d->trans = d->realtrans + 1;
  1821.     REALLOC(d->fails, int *, d->tralloc);
  1822.     REALLOC(d->success, int, d->tralloc);
  1823.     REALLOC(d->newlines, int, d->tralloc);
  1824.     while (oldalloc < d->tralloc)
  1825.       {
  1826.         d->trans[oldalloc] = NULL;
  1827.         d->fails[oldalloc++] = NULL;
  1828.       }
  1829.       }
  1830.  
  1831.   /* Keep the newline transition in a special place so we can use it as
  1832.      a sentinel. */
  1833.   d->newlines[s] = trans['\n'];
  1834.   trans['\n'] = -1;
  1835.  
  1836.   if (ACCEPTING(s, *d))
  1837.     d->fails[s] = trans;
  1838.   else
  1839.     d->trans[s] = trans;
  1840. }
  1841.  
  1842. static void
  1843. build_state_zero(d)
  1844.      struct dfa *d;
  1845. {
  1846.   d->tralloc = 1;
  1847.   d->trcount = 0;
  1848.   CALLOC(d->realtrans, int *, d->tralloc + 1);
  1849.   d->trans = d->realtrans + 1;
  1850.   CALLOC(d->fails, int *, d->tralloc);
  1851.   MALLOC(d->success, int, d->tralloc);
  1852.   MALLOC(d->newlines, int, d->tralloc);
  1853.   build_state(0, d);
  1854. }
  1855.  
  1856. /* Search through a buffer looking for a match to the given struct dfa.
  1857.    Find the first occurrence of a string matching the regexp in the buffer,
  1858.    and the shortest possible version thereof.  Return a pointer to the first
  1859.    character after the match, or NULL if none is found.  Begin points to
  1860.    the beginning of the buffer, and end points to the first character after
  1861.    its end.  We store a newline in *end to act as a sentinel, so end had
  1862.    better point somewhere valid.  Newline is a flag indicating whether to
  1863.    allow newlines to be in the matching string.  If count is non-
  1864.    NULL it points to a place we're supposed to increment every time we
  1865.    see a newline.  Finally, if backref is non-NULL it points to a place
  1866.    where we're supposed to store a 1 if backreferencing happened and the
  1867.    match needs to be verified by a backtracking matcher.  Otherwise
  1868.    we store a 0 in *backref. */
  1869. char *
  1870. dfaexec(d, begin, end, newline, count, backref)
  1871.      struct dfa *d;
  1872.      char *begin;
  1873.      char *end;
  1874.      int newline;
  1875.      int *count;
  1876.      int *backref;
  1877. {
  1878.   register int s, s1, tmp;    /* Current state. */
  1879.   register unsigned char *p;    /* Current input character. */
  1880.   register int **trans, *t;    /* Copy of d->trans so it can be optimized
  1881.                    into a register. */
  1882.   static int sbit[NOTCHAR];    /* Table for anding with d->success. */
  1883.   static int sbit_init;
  1884.  
  1885.   if (! sbit_init)
  1886.     {
  1887.       int i;
  1888.  
  1889.       sbit_init = 1;
  1890.       for (i = 0; i < NOTCHAR; ++i)
  1891.     sbit[i] = (ISALNUM(i)) ? 2 : 1;
  1892.       sbit['\n'] = 4;
  1893.     }
  1894.  
  1895.   if (! d->tralloc)
  1896.     build_state_zero(d);
  1897.  
  1898.   s = s1 = 0;
  1899.   p = (unsigned char *) begin;
  1900.   trans = d->trans;
  1901.   *end = '\n';
  1902.  
  1903.   for (;;)
  1904.     {
  1905.       while ((t = trans[s]) != 0) { /* hand-optimized loop */
  1906.     s1 = t[*p++];
  1907.         if ((t = trans[s1]) == 0) {
  1908.            tmp = s ; s = s1 ; s1 = tmp ; /* swap */
  1909.            break;
  1910.         }
  1911.     s = t[*p++];
  1912.       }
  1913.  
  1914.       if (s >= 0 && p <= (unsigned char *) end && d->fails[s])
  1915.     {
  1916.       if (d->success[s] & sbit[*p])
  1917.         {
  1918.           if (backref)
  1919.         *backref = (d->states[s].backref != 0);
  1920.           return (char *) p;
  1921.         }
  1922.  
  1923.       s1 = s;
  1924.       s = d->fails[s][*p++];
  1925.       continue;
  1926.     }
  1927.  
  1928.       /* If the previous character was a newline, count it. */
  1929.       if (count && (char *) p <= end && p[-1] == '\n')
  1930.     ++*count;
  1931.  
  1932.       /* Check if we've run off the end of the buffer. */
  1933.       if ((char *) p > end)
  1934.     return NULL;
  1935.  
  1936.       if (s >= 0)
  1937.     {
  1938.       build_state(s, d);
  1939.       trans = d->trans;
  1940.       continue;
  1941.     }
  1942.  
  1943.       if (p[-1] == '\n' && newline)
  1944.     {
  1945.       s = d->newlines[s1];
  1946.       continue;
  1947.     }
  1948.  
  1949.       s = 0;
  1950.     }
  1951. }
  1952.  
  1953. /* Initialize the components of a dfa that the other routines don't
  1954.    initialize for themselves. */
  1955. void
  1956. dfainit(d)
  1957.      struct dfa *d;
  1958. {
  1959.   d->calloc = 1;
  1960.   MALLOC(d->charclasses, charclass, d->calloc);
  1961.   d->cindex = 0;
  1962.  
  1963.   d->talloc = 1;
  1964.   MALLOC(d->tokens, token, d->talloc);
  1965.   d->tindex = d->depth = d->nleaves = d->nregexps = 0;
  1966.  
  1967.   d->searchflag = 0;
  1968.   d->tralloc = 0;
  1969.  
  1970.   d->musts = 0;
  1971. }
  1972.  
  1973. /* Parse and analyze a single string of the given length. */
  1974. void
  1975. dfacomp(s, len, d, searchflag)
  1976.      char *s;
  1977.      size_t len;
  1978.      struct dfa *d;
  1979.      int searchflag;
  1980. {
  1981.   if (case_fold)    /* dummy folding in service of dfamust() */
  1982.     {
  1983.       char *lcopy;
  1984.       int i;
  1985.  
  1986.       lcopy = malloc(len);
  1987.       if (!lcopy)
  1988.     dfaerror(_("out of memory"));
  1989.       
  1990.       /* This is a kludge. */
  1991.       case_fold = 0;
  1992.       for (i = 0; i < len; ++i)
  1993.     if (ISUPPER(s[i]))
  1994.       lcopy[i] = tolower(s[i]);
  1995.     else
  1996.       lcopy[i] = s[i];
  1997.  
  1998.       dfainit(d);
  1999.       dfaparse(lcopy, len, d);
  2000.       free(lcopy);
  2001.       dfamust(d);
  2002.       d->cindex = d->tindex = d->depth = d->nleaves = d->nregexps = 0;
  2003.       case_fold = 1;
  2004.       dfaparse(s, len, d);
  2005.       dfaanalyze(d, searchflag);
  2006.     }
  2007.   else
  2008.     {
  2009.         dfainit(d);
  2010.         dfaparse(s, len, d);
  2011.     dfamust(d);
  2012.         dfaanalyze(d, searchflag);
  2013.     }
  2014. }
  2015.  
  2016. /* Free the storage held by the components of a dfa. */
  2017. void
  2018. dfafree(d)
  2019.      struct dfa *d;
  2020. {
  2021.   int i;
  2022.   struct dfamust *dm, *ndm;
  2023.  
  2024.   free((ptr_t) d->charclasses);
  2025.   free((ptr_t) d->tokens);
  2026.   for (i = 0; i < d->sindex; ++i)
  2027.     free((ptr_t) d->states[i].elems.elems);
  2028.   free((ptr_t) d->states);
  2029.   for (i = 0; i < d->tindex; ++i)
  2030.     if (d->follows[i].elems)
  2031.       free((ptr_t) d->follows[i].elems);
  2032.   free((ptr_t) d->follows);
  2033.   for (i = 0; i < d->tralloc; ++i)
  2034.     if (d->trans[i])
  2035.       free((ptr_t) d->trans[i]);
  2036.     else if (d->fails[i])
  2037.       free((ptr_t) d->fails[i]);
  2038.   if (d->realtrans) free((ptr_t) d->realtrans);
  2039.   if (d->fails) free((ptr_t) d->fails);
  2040.   if (d->newlines) free((ptr_t) d->newlines);
  2041.   if (d->success) free((ptr_t) d->success);
  2042.   for (dm = d->musts; dm; dm = ndm)
  2043.     {
  2044.       ndm = dm->next;
  2045.       free(dm->must);
  2046.       free((ptr_t) dm);
  2047.     }
  2048. }
  2049.  
  2050. /* Having found the postfix representation of the regular expression,
  2051.    try to find a long sequence of characters that must appear in any line
  2052.    containing the r.e.
  2053.    Finding a "longest" sequence is beyond the scope here;
  2054.    we take an easy way out and hope for the best.
  2055.    (Take "(ab|a)b"--please.)
  2056.  
  2057.    We do a bottom-up calculation of sequences of characters that must appear
  2058.    in matches of r.e.'s represented by trees rooted at the nodes of the postfix
  2059.    representation:
  2060.     sequences that must appear at the left of the match ("left")
  2061.     sequences that must appear at the right of the match ("right")
  2062.     lists of sequences that must appear somewhere in the match ("in")
  2063.     sequences that must constitute the match ("is")
  2064.  
  2065.    When we get to the root of the tree, we use one of the longest of its
  2066.    calculated "in" sequences as our answer.  The sequence we find is returned in
  2067.    d->must (where "d" is the single argument passed to "dfamust");
  2068.    the length of the sequence is returned in d->mustn.
  2069.  
  2070.    The sequences calculated for the various types of node (in pseudo ANSI c)
  2071.    are shown below.  "p" is the operand of unary operators (and the left-hand
  2072.    operand of binary operators); "q" is the right-hand operand of binary
  2073.    operators.
  2074.  
  2075.    "ZERO" means "a zero-length sequence" below.
  2076.  
  2077.     Type    left        right        is        in
  2078.     ----    ----        -----        --        --
  2079.     char c    # c        # c        # c        # c
  2080.     
  2081.     CSET    ZERO        ZERO        ZERO        ZERO
  2082.     
  2083.     STAR    ZERO        ZERO        ZERO        ZERO
  2084.  
  2085.     QMARK    ZERO        ZERO        ZERO        ZERO
  2086.  
  2087.     PLUS    p->left        p->right    ZERO        p->in
  2088.  
  2089.     CAT    (p->is==ZERO)?    (q->is==ZERO)?    (p->is!=ZERO &&    p->in plus
  2090.         p->left :    q->right :    q->is!=ZERO) ?    q->in plus
  2091.         p->is##q->left    p->right##q->is    p->is##q->is :    p->right##q->left
  2092.                         ZERO
  2093.                     
  2094.     OR    longest common    longest common    (do p->is and    substrings common to
  2095.         leading        trailing    q->is have same    p->in and q->in
  2096.         (sub)sequence    (sub)sequence    length and    
  2097.         of p->left    of p->right    content) ?    
  2098.         and q->left    and q->right    p->is : NULL    
  2099.  
  2100.    If there's anything else we recognize in the tree, all four sequences get set
  2101.    to zero-length sequences.  If there's something we don't recognize in the tree,
  2102.    we just return a zero-length sequence.
  2103.  
  2104.    Break ties in favor of infrequent letters (choosing 'zzz' in preference to
  2105.    'aaa')?
  2106.  
  2107.    And. . .is it here or someplace that we might ponder "optimizations" such as
  2108.     egrep 'psi|epsilon'    ->    egrep 'psi'
  2109.     egrep 'pepsi|epsilon'    ->    egrep 'epsi'
  2110.                     (Yes, we now find "epsi" as a "string
  2111.                     that must occur", but we might also
  2112.                     simplify the *entire* r.e. being sought)
  2113.     grep '[c]'        ->    grep 'c'
  2114.     grep '(ab|a)b'        ->    grep 'ab'
  2115.     grep 'ab*'        ->    grep 'a'
  2116.     grep 'a*b'        ->    grep 'b'
  2117.  
  2118.    There are several issues:
  2119.  
  2120.    Is optimization easy (enough)?
  2121.  
  2122.    Does optimization actually accomplish anything,
  2123.    or is the automaton you get from "psi|epsilon" (for example)
  2124.    the same as the one you get from "psi" (for example)?
  2125.   
  2126.    Are optimizable r.e.'s likely to be used in real-life situations
  2127.    (something like 'ab*' is probably unlikely; something like is
  2128.    'psi|epsilon' is likelier)? */
  2129.  
  2130. static char *
  2131. icatalloc(old, new)
  2132.      char *old;
  2133.      char *new;
  2134. {
  2135.   char *result;
  2136.   size_t oldsize, newsize;
  2137.  
  2138.   newsize = (new == NULL) ? 0 : strlen(new);
  2139.   if (old == NULL)
  2140.     oldsize = 0;
  2141.   else if (newsize == 0)
  2142.     return old;
  2143.   else    oldsize = strlen(old);
  2144.   if (old == NULL)
  2145.     result = (char *) malloc(newsize + 1);
  2146.   else
  2147.     result = (char *) realloc((void *) old, oldsize + newsize + 1);
  2148.   if (result != NULL && new != NULL)
  2149.     (void) strcpy(result + oldsize, new);
  2150.   return result;
  2151. }
  2152.  
  2153. static char *
  2154. icpyalloc(string)
  2155.      char *string;
  2156. {
  2157.   return icatalloc((char *) NULL, string);
  2158. }
  2159.  
  2160. static char *
  2161. istrstr(lookin, lookfor)
  2162.      char *lookin;
  2163.      char *lookfor;
  2164. {
  2165.   char *cp;
  2166.   size_t len;
  2167.  
  2168.   len = strlen(lookfor);
  2169.   for (cp = lookin; *cp != '\0'; ++cp)
  2170.     if (strncmp(cp, lookfor, len) == 0)
  2171.       return cp;
  2172.   return NULL;
  2173. }
  2174.  
  2175. static void
  2176. ifree(cp)
  2177.      char *cp;
  2178. {
  2179.   if (cp != NULL)
  2180.     free(cp);
  2181. }
  2182.  
  2183. static void
  2184. freelist(cpp)
  2185.      char **cpp;
  2186. {
  2187.   int i;
  2188.  
  2189.   if (cpp == NULL)
  2190.     return;
  2191.   for (i = 0; cpp[i] != NULL; ++i)
  2192.     {
  2193.       free(cpp[i]);
  2194.       cpp[i] = NULL;
  2195.     }
  2196. }
  2197.  
  2198. static char **
  2199. enlist(cpp, new, len)
  2200.      char **cpp;
  2201.      char *new;
  2202.      size_t len;
  2203. {
  2204.   int i, j;
  2205.  
  2206.   if (cpp == NULL)
  2207.     return NULL;
  2208.   if ((new = icpyalloc(new)) == NULL)
  2209.     {
  2210.       freelist(cpp);
  2211.       return NULL;
  2212.     }
  2213.   new[len] = '\0';
  2214.   /* Is there already something in the list that's new (or longer)? */
  2215.   for (i = 0; cpp[i] != NULL; ++i)
  2216.     if (istrstr(cpp[i], new) != NULL)
  2217.       {
  2218.     free(new);
  2219.     return cpp;
  2220.       }
  2221.   /* Eliminate any obsoleted strings. */
  2222.   j = 0;
  2223.   while (cpp[j] != NULL)
  2224.     if (istrstr(new, cpp[j]) == NULL)
  2225.       ++j;
  2226.     else
  2227.       {
  2228.     free(cpp[j]);
  2229.     if (--i == j)
  2230.       break;
  2231.     cpp[j] = cpp[i];
  2232.     cpp[i] = NULL;
  2233.       }
  2234.   /* Add the new string. */
  2235.   cpp = (char **) realloc((char *) cpp, (i + 2) * sizeof *cpp);
  2236.   if (cpp == NULL)
  2237.     return NULL;
  2238.   cpp[i] = new;
  2239.   cpp[i + 1] = NULL;
  2240.   return cpp;
  2241. }
  2242.  
  2243. /* Given pointers to two strings, return a pointer to an allocated
  2244.    list of their distinct common substrings. Return NULL if something
  2245.    seems wild. */
  2246. static char **
  2247. comsubs(left, right)
  2248.      char *left;
  2249.      char *right;
  2250. {
  2251.   char **cpp;
  2252.   char *lcp;
  2253.   char *rcp;
  2254.   size_t i, len;
  2255.  
  2256.   if (left == NULL || right == NULL)
  2257.     return NULL;
  2258.   cpp = (char **) malloc(sizeof *cpp);
  2259.   if (cpp == NULL)
  2260.     return NULL;
  2261.   cpp[0] = NULL;
  2262.   for (lcp = left; *lcp != '\0'; ++lcp)
  2263.     {
  2264.       len = 0;
  2265.       rcp = index(right, *lcp);
  2266.       while (rcp != NULL)
  2267.     {
  2268.       for (i = 1; lcp[i] != '\0' && lcp[i] == rcp[i]; ++i)
  2269.         continue;
  2270.       if (i > len)
  2271.         len = i;
  2272.       rcp = index(rcp + 1, *lcp);
  2273.     }
  2274.       if (len == 0)
  2275.     continue;
  2276.       if ((cpp = enlist(cpp, lcp, len)) == NULL)
  2277.     break;
  2278.     }
  2279.   return cpp;
  2280. }
  2281.  
  2282. static char **
  2283. addlists(old, new)
  2284. char **old;
  2285. char **new;
  2286. {
  2287.   int i;
  2288.  
  2289.   if (old == NULL || new == NULL)
  2290.     return NULL;
  2291.   for (i = 0; new[i] != NULL; ++i)
  2292.     {
  2293.       old = enlist(old, new[i], strlen(new[i]));
  2294.       if (old == NULL)
  2295.     break;
  2296.     }
  2297.   return old;
  2298. }
  2299.  
  2300. /* Given two lists of substrings, return a new list giving substrings
  2301.    common to both. */
  2302. static char **
  2303. inboth(left, right)
  2304.      char **left;
  2305.      char **right;
  2306. {
  2307.   char **both;
  2308.   char **temp;
  2309.   int lnum, rnum;
  2310.  
  2311.   if (left == NULL || right == NULL)
  2312.     return NULL;
  2313.   both = (char **) malloc(sizeof *both);
  2314.   if (both == NULL)
  2315.     return NULL;
  2316.   both[0] = NULL;
  2317.   for (lnum = 0; left[lnum] != NULL; ++lnum)
  2318.     {
  2319.       for (rnum = 0; right[rnum] != NULL; ++rnum)
  2320.     {
  2321.       temp = comsubs(left[lnum], right[rnum]);
  2322.       if (temp == NULL)
  2323.         {
  2324.           freelist(both);
  2325.           return NULL;
  2326.         }
  2327.       both = addlists(both, temp);
  2328.       freelist(temp);
  2329.       free(temp);
  2330.       if (both == NULL)
  2331.         return NULL;
  2332.     }
  2333.     }
  2334.   return both;
  2335. }
  2336.  
  2337. typedef struct
  2338. {
  2339.   char **in;
  2340.   char *left;
  2341.   char *right;
  2342.   char *is;
  2343. } must;
  2344.  
  2345. static void
  2346. resetmust(mp)
  2347. must *mp;
  2348. {
  2349.   mp->left[0] = mp->right[0] = mp->is[0] = '\0';
  2350.   freelist(mp->in);
  2351. }
  2352.  
  2353. static void
  2354. dfamust(dfa)
  2355. struct dfa *dfa;
  2356. {
  2357.   must *musts;
  2358.   must *mp;
  2359.   char *result;
  2360.   int ri;
  2361.   int i;
  2362.   int exact;
  2363.   token t;
  2364.   static must must0;
  2365.   struct dfamust *dm;
  2366.   static char empty_string[] = "";
  2367.  
  2368.   result = empty_string;
  2369.   exact = 0;
  2370.   musts = (must *) malloc((dfa->tindex + 1) * sizeof *musts);
  2371.   if (musts == NULL)
  2372.     return;
  2373.   mp = musts;
  2374.   for (i = 0; i <= dfa->tindex; ++i)
  2375.     mp[i] = must0;
  2376.   for (i = 0; i <= dfa->tindex; ++i)
  2377.     {
  2378.       mp[i].in = (char **) malloc(sizeof *mp[i].in);
  2379.       mp[i].left = malloc(2);
  2380.       mp[i].right = malloc(2);
  2381.       mp[i].is = malloc(2);
  2382.       if (mp[i].in == NULL || mp[i].left == NULL ||
  2383.       mp[i].right == NULL || mp[i].is == NULL)
  2384.     goto done;
  2385.       mp[i].left[0] = mp[i].right[0] = mp[i].is[0] = '\0';
  2386.       mp[i].in[0] = NULL;
  2387.     }
  2388. #ifdef DEBUG
  2389.   fprintf(stderr, "dfamust:\n");
  2390.   for (i = 0; i < dfa->tindex; ++i)
  2391.     {
  2392.       fprintf(stderr, " %d:", i);
  2393.       prtok(dfa->tokens[i]);
  2394.     }
  2395.   putc('\n', stderr);
  2396. #endif
  2397.   for (ri = 0; ri < dfa->tindex; ++ri)
  2398.     {
  2399.       switch (t = dfa->tokens[ri])
  2400.     {
  2401.     case LPAREN:
  2402.     case RPAREN:
  2403.       goto done;        /* "cannot happen" */
  2404.     case EMPTY:
  2405.     case BEGLINE:
  2406.     case ENDLINE:
  2407.     case BEGWORD:
  2408.     case ENDWORD:
  2409.     case LIMWORD:
  2410.     case NOTLIMWORD:
  2411.     case BACKREF:
  2412.       resetmust(mp);
  2413.       break;
  2414.     case STAR:
  2415.     case QMARK:
  2416.       if (mp <= musts)
  2417.         goto done;        /* "cannot happen" */
  2418.       --mp;
  2419.       resetmust(mp);
  2420.       break;
  2421.     case OR:
  2422.     case ORTOP:
  2423.       if (mp < &musts[2])
  2424.         goto done;        /* "cannot happen" */
  2425.       {
  2426.         char **new;
  2427.         must *lmp;
  2428.         must *rmp;
  2429.         int j, ln, rn, n;
  2430.  
  2431.         rmp = --mp;
  2432.         lmp = --mp;
  2433.         /* Guaranteed to be.  Unlikely, but. . . */
  2434.         if (strcmp(lmp->is, rmp->is) != 0)
  2435.           lmp->is[0] = '\0';
  2436.         /* Left side--easy */
  2437.         i = 0;
  2438.         while (lmp->left[i] != '\0' && lmp->left[i] == rmp->left[i])
  2439.           ++i;
  2440.         lmp->left[i] = '\0';
  2441.         /* Right side */
  2442.         ln = strlen(lmp->right);
  2443.         rn = strlen(rmp->right);
  2444.         n = ln;
  2445.         if (n > rn)
  2446.           n = rn;
  2447.         for (i = 0; i < n; ++i)
  2448.           if (lmp->right[ln - i - 1] != rmp->right[rn - i - 1])
  2449.         break;
  2450.         for (j = 0; j < i; ++j)
  2451.           lmp->right[j] = lmp->right[(ln - i) + j];
  2452.         lmp->right[j] = '\0';
  2453.         new = inboth(lmp->in, rmp->in);
  2454.         if (new == NULL)
  2455.           goto done;
  2456.         freelist(lmp->in);
  2457.         free((char *) lmp->in);
  2458.         lmp->in = new;
  2459.       }
  2460.       break;
  2461.     case PLUS:
  2462.       if (mp <= musts)
  2463.         goto done;        /* "cannot happen" */
  2464.       --mp;
  2465.       mp->is[0] = '\0';
  2466.       break;
  2467.     case END:
  2468.       if (mp != &musts[1])
  2469.         goto done;        /* "cannot happen" */
  2470.       for (i = 0; musts[0].in[i] != NULL; ++i)
  2471.         if (strlen(musts[0].in[i]) > strlen(result))
  2472.           result = musts[0].in[i];
  2473.       if (strcmp(result, musts[0].is) == 0)
  2474.         exact = 1;
  2475.       goto done;
  2476.     case CAT:
  2477.       if (mp < &musts[2])
  2478.         goto done;        /* "cannot happen" */
  2479.       {
  2480.         must *lmp;
  2481.         must *rmp;
  2482.  
  2483.         rmp = --mp;
  2484.         lmp = --mp;
  2485.         /* In.  Everything in left, plus everything in
  2486.            right, plus catenation of
  2487.            left's right and right's left. */
  2488.         lmp->in = addlists(lmp->in, rmp->in);
  2489.         if (lmp->in == NULL)
  2490.           goto done;
  2491.         if (lmp->right[0] != '\0' &&
  2492.         rmp->left[0] != '\0')
  2493.           {
  2494.         char *tp;
  2495.  
  2496.         tp = icpyalloc(lmp->right);
  2497.         if (tp == NULL)
  2498.           goto done;
  2499.         tp = icatalloc(tp, rmp->left);
  2500.         if (tp == NULL)
  2501.           goto done;
  2502.         lmp->in = enlist(lmp->in, tp,
  2503.                  strlen(tp));
  2504.         free(tp);
  2505.         if (lmp->in == NULL)
  2506.           goto done;
  2507.           }
  2508.         /* Left-hand */
  2509.         if (lmp->is[0] != '\0')
  2510.           {
  2511.         lmp->left = icatalloc(lmp->left,
  2512.                       rmp->left);
  2513.         if (lmp->left == NULL)
  2514.           goto done;
  2515.           }
  2516.         /* Right-hand */
  2517.         if (rmp->is[0] == '\0')
  2518.           lmp->right[0] = '\0';
  2519.         lmp->right = icatalloc(lmp->right, rmp->right);
  2520.         if (lmp->right == NULL)
  2521.           goto done;
  2522.         /* Guaranteed to be */
  2523.         if (lmp->is[0] != '\0' && rmp->is[0] != '\0')
  2524.           {
  2525.         lmp->is = icatalloc(lmp->is, rmp->is);
  2526.         if (lmp->is == NULL)
  2527.           goto done;
  2528.           }
  2529.         else
  2530.           lmp->is[0] = '\0';
  2531.       }
  2532.       break;
  2533.     default:
  2534.       if (t < END)
  2535.         {
  2536.           /* "cannot happen" */
  2537.           goto done;
  2538.         }
  2539.       else if (t == '\0')
  2540.         {
  2541.           /* not on *my* shift */
  2542.           goto done;
  2543.         }
  2544.       else if (t >= CSET)
  2545.         {
  2546.           /* easy enough */
  2547.           resetmust(mp);
  2548.         }
  2549.       else
  2550.         {
  2551.           /* plain character */
  2552.           resetmust(mp);
  2553.           mp->is[0] = mp->left[0] = mp->right[0] = t;
  2554.           mp->is[1] = mp->left[1] = mp->right[1] = '\0';
  2555.           mp->in = enlist(mp->in, mp->is, (size_t)1);
  2556.           if (mp->in == NULL)
  2557.         goto done;
  2558.         }
  2559.       break;
  2560.     }
  2561. #ifdef DEBUG
  2562.       fprintf(stderr, " node: %d:", ri);
  2563.       prtok(dfa->tokens[ri]);
  2564.       fprintf(stderr, "\n  in:");
  2565.       for (i = 0; mp->in[i]; ++i)
  2566.     fprintf(stderr, " \"%s\"", mp->in[i]);
  2567.       fprintf(stderr, "\n  is: \"%s\"\n", mp->is);
  2568.       fprintf(stderr, "  left: \"%s\"\n", mp->left);
  2569.       fprintf(stderr, "  right: \"%s\"\n", mp->right);
  2570. #endif
  2571.       ++mp;
  2572.     }
  2573.  done:
  2574.   if (strlen(result))
  2575.     {
  2576.       dm = (struct dfamust *) malloc(sizeof (struct dfamust));
  2577.       dm->exact = exact;
  2578.       dm->must = malloc(strlen(result) + 1);
  2579.       strcpy(dm->must, result);
  2580.       dm->next = dfa->musts;
  2581.       dfa->musts = dm;
  2582.     }
  2583.   mp = musts;
  2584.   for (i = 0; i <= dfa->tindex; ++i)
  2585.     {
  2586.       freelist(mp[i].in);
  2587.       ifree((char *) mp[i].in);
  2588.       ifree(mp[i].left);
  2589.       ifree(mp[i].right);
  2590.       ifree(mp[i].is);
  2591.     }
  2592.   free((char *) mp);
  2593. }
  2594.